package top.sssd.spi.pf4j;

import org.pf4j.PluginManager;
import org.pf4j.PluginWrapper;
import top.sssd.spi.pf4j.api.GreetingService;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) throws IOException {
        PluginManager pluginManager = new GreetingPluginManger();

        Path pluginsDir = Paths.get("plugins");
        if (!Files.exists(pluginsDir)) {
            Files.createDirectories(pluginsDir);
        }

        // 加载插件目录中的所有插件
        pluginManager.loadPlugins();

        // 启动所有插件
        pluginManager.startPlugins();

        List<GreetingService> services = pluginManager.getExtensions(GreetingService.class);
        services.forEach(item -> item.sayHello("sssd"));

        List<PluginWrapper> startedPlugins = pluginManager.getStartedPlugins();
        for (PluginWrapper plugin : startedPlugins) {
            String pluginId = plugin.getDescriptor().getPluginId();
            System.out.println("Extensions added by plugin:" + pluginId);
            Set<String> extensionClassNames = pluginManager.getExtensionClassNames(pluginId);
            for (String extension : extensionClassNames) {
                System.out.println("extension:" + extension);
            }
        }

        for (PluginWrapper plugin : startedPlugins) {
            String pluginId = plugin.getDescriptor().getPluginId();
            System.out.println("Extensions instances added by plugin +" + pluginId + " for extension point :" + GreetingService.class.getName());
            List<GreetingService> extensions = pluginManager.getExtensions(GreetingService.class, pluginId);
            for (Object extension : extensions) {
                System.out.println("extension:" + extension);
            }
        }

        pluginManager.stopPlugins();
    }
}
